package com.razerzone.android.fitness;

import iterface.ITaskCallBacks;
import utils.Utils;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import app.fitness.fragment.AboutFragment;
import app.fitness.fragment.DashBoardDetailFragment;
import app.fitness.fragment.DashBoardFragment;
import app.fitness.fragment.GoalSettingsFragment;
import app.fitness.fragment.SplashScreenFragment;

import com.razer.android.nabuopensdk.NabuOpenSDK;

import define.Class;
import define.Constants;
import define.Language;

public class ActivityFitness extends FragmentActivity implements ITaskCallBacks {
	/**
	 * Data section
	 */
	/**
	 * Interface section
	 */
	@Override
	public void onBeginReceiveData() {
		// Show loading dialog when begin get data from server
		if (mPd != null) {
			mPd.show();
		}
	}

	@Override
	public void onCompleteReceiveData() {
		if (mPd.isShowing()) {
			mPd.dismiss();
		}
	}

	/**
	 * String section
	 */
	private boolean IS_PRESS_BACK_TWICE = false;

	// private static String TITLE = null;

	/**
	 * View section
	 */
	public static ActionBarDrawerToggle mAbdtToggle;
	public static Button mBtnLeftActionBar;
	// private Dialog mDialogScanDevice;
	private DrawerLayout mDlDrawer;
	// public static ImageButton mIbtnRightActionBar;
	public static ImageButton mIbtnAvatarInDrawer;
	public static ImageView mIvActionBar;
	public static LinearLayout mLLAbout;
	public static LinearLayout mLLDashBoard;
	// public static LinearLayout mLLDevice;
	// private LinearLayout mLLFriends;
	public static LinearLayout mLLLeftActionBar;
	// private LinearLayout mLLLogOff;
	public static LinearLayout mLLGoalSettings;
	private LinearLayout mLlUserProfile;
	private ProgressDialog mPd;
	public static TextView mTvNickNameBesideAvatar;
	public static TextView mTvNickNameBesideDevice;
	public static TextView mTvTitle;

	/**
	 * Other tools
	 */
	public static Context mContextActivityFitness;
	public static FragmentManager mFm;

	private void onClickBack() {
		if (mTvTitle.getText().toString()
				.equals(getString(R.string.dashboard_))) {
			/**
			 * Current page is Dash board
			 */
			/**
			 * Press Back twice to exit
			 */
			if (IS_PRESS_BACK_TWICE) {
				// Exit the application
				android.os.Process.killProcess(android.os.Process.myPid());
			}

			IS_PRESS_BACK_TWICE = true;
			Toast.makeText(this,
					getString(R.string.pressed_back_twice_to_exit),
					Toast.LENGTH_SHORT).show();

			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					IS_PRESS_BACK_TWICE = false;
				}
			}, 2000);
		} else {
			/**
			 * The other pages, should be back to Dash board Fragment page
			 */
			getSupportFragmentManager().popBackStack();

			Fragment mFragmentCurrent = getSupportFragmentManager()
					.findFragmentById(R.id.fr_content_activity_fitness);
			if (mFragmentCurrent != null) {
				mFm.beginTransaction().remove(mFragmentCurrent)
						.commitAllowingStateLoss();
			}

			if (mFragmentCurrent.getClass().getSimpleName().toString()
					.equals(AboutFragment.class.getSimpleName())) {
				/**
				 * About page
				 */
				/**
				 * Check Title in About Fragment page to decide where need to go
				 */
				if (mTvTitle.getText().toString().equals(Class.EULA)) {
					// Insert the fragment by replacing any existing
					// fragment
					getSupportFragmentManager()
							.beginTransaction()
							.replace(R.id.fr_content_activity_fitness,
									new AboutFragment())
							.addToBackStack(AboutFragment.TAG)
							.commitAllowingStateLoss();
				} else if (mTvTitle.getText().toString()
						.equals(Class.OPEN_SOURCE_NOTICES)) {
					// Insert the fragment by replacing any existing
					// fragment
					getSupportFragmentManager()
							.beginTransaction()
							.replace(R.id.fr_content_activity_fitness,
									new AboutFragment())
							.addToBackStack(AboutFragment.TAG)
							.commitAllowingStateLoss();
				} else if (mTvTitle.getText().toString()
						.equals(getString(R.string.about_))) {
					// Insert the fragment by replacing any existing
					// fragment
					getSupportFragmentManager()
							.beginTransaction()
							.replace(R.id.fr_content_activity_fitness,
									new DashBoardFragment())
							.addToBackStack(DashBoardFragment.TAG)
							.commitAllowingStateLoss();
				}
			} else if (mFragmentCurrent.getClass().getSimpleName().toString()
					.equals(DashBoardDetailFragment.class.getSimpleName())) {
				/**
				 * Dash Board Detail page
				 */
				/**
				 * Save all value into single ton before go to Dash board page
				 * from Dash board detail page
				 */
				DashBoardDetailFragment.IS_GO_TO_DASHBOARD_FROM_DASHBOARD_DETAIL = true;

				DashBoardDetailFragment.saveAllDataIntoSingleTon();
			} else if (mFragmentCurrent.getClass().getSimpleName().toString()
					.equals(GoalSettingsFragment.class.getSimpleName())) {
				/**
				 * Goal page
				 */
				// Insert the fragment by replacing any existing
				// fragment
				getSupportFragmentManager()
						.beginTransaction()
						.replace(R.id.fr_content_activity_fitness,
								new DashBoardFragment())
						.addToBackStack(DashBoardFragment.TAG)
						.commitAllowingStateLoss();
			}
		}
	}

	/**
	 * On clicked
	 * 
	 * @param v
	 */
	public void onClickFitness(View v) {
		int background_drawer_item = getResources().getColor(R.color.green);
		// Create a new fragment and specify the planet to show based on
		// position
		switch (v.getId()) {
		case R.id.tv_about_in_fitness:
			// Set background color for drawer item when was chose
			mLLAbout.setBackgroundColor(background_drawer_item);
			mLLDashBoard.setBackgroundColor(Color.TRANSPARENT);
			mLLGoalSettings.setBackgroundColor(Color.TRANSPARENT);
			mLlUserProfile.setBackgroundColor(Color.TRANSPARENT);

			// Show action bar
			getActionBar().show();

			// Set title of menu is Dash board
			// Insert the fragment by replacing any existing fragment
			getSupportFragmentManager()
					.beginTransaction()
					.replace(R.id.fr_content_activity_fitness,
							new AboutFragment())
					.addToBackStack(AboutFragment.TAG)
					.commitAllowingStateLoss();

			setTitle(getString(R.string.about_));
			break;
		case R.id.tv_dash_board_in_fitness:
			// Set background color for drawer item when was chose
			mLLAbout.setBackgroundColor(Color.TRANSPARENT);
			mLLDashBoard.setBackgroundColor(background_drawer_item);
			mLLGoalSettings.setBackgroundColor(Color.TRANSPARENT);
			mLlUserProfile.setBackgroundColor(Color.TRANSPARENT);

			// Show action bar
			getActionBar().show();

			// Set title of menu is Dash board
			// Insert the fragment by replacing any existing fragment
			getSupportFragmentManager()
					.beginTransaction()
					.replace(R.id.fr_content_activity_fitness,
							new DashBoardFragment())
					.addToBackStack(DashBoardFragment.TAG)
					.commitAllowingStateLoss();

			setTitle(getString(R.string.dashboard_));
			break;
		case R.id.tv_goal_settings_in_fitness:
			// Set background color for drawer item when was chose
			mLLAbout.setBackgroundColor(Color.TRANSPARENT);
			mLLDashBoard.setBackgroundColor(Color.TRANSPARENT);
			mLLGoalSettings.setBackgroundColor(background_drawer_item);
			mLlUserProfile.setBackgroundColor(Color.TRANSPARENT);

			// Show action bar
			getActionBar().show();

			// Set title of menu is Settings
			getSupportFragmentManager()
					.beginTransaction()
					.replace(R.id.fr_content_activity_fitness,
							new GoalSettingsFragment())
					.addToBackStack(GoalSettingsFragment.TAG)
					.commitAllowingStateLoss();

			setTitle(getString(R.string.goal_settings_));
			break;
		default:
			break;
		}

		// Close the navigation drawer
		mDlDrawer.closeDrawers();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_fitness);

		mContextActivityFitness = ActivityFitness.this;

		/**
		 * Set only English language, no more. If changed to the others
		 * language, still used English language
		 */
		// Utils.setDefaultLanguage(this, Locale.ENGLISH.getDisplayLanguage());

		if (Constants.IS_FIRST_TIME_OPEN_APP) {
			Constants.IS_FIRST_TIME_OPEN_APP = false;

			switch (Utils.checkLanguageInSettings()) {
			case Language.CHINESE:
				Constants.CURRENT_LANGUAGE_SYSTEM = Language.CHINESE;
				break;
			case Language.ENGLISH:
				Constants.CURRENT_LANGUAGE_SYSTEM = Language.ENGLISH;
				break;
			}
		}

		// Initialize SDK
		Constants.nabuSDK = NabuOpenSDK.getInstance(this);

		// Initialize progress dialog
		mPd = new ProgressDialog(this, AlertDialog.THEME_HOLO_DARK);
		mPd.setMessage(getString(R.string.data_sync));

		// Get fragment manager
		mFm = getSupportFragmentManager();

		/**
		 * Setup action bar
		 */
		setupActionBar();

		// Hide action bar
		if (getActionBar().isShowing()) {
			getActionBar().hide();
		}

		// Initial Connectivity tool
		Constants.utils = new Utils(mContextActivityFitness);

		// Initial variables & variables
		initialVariables();
		initialData(savedInstanceState);

		// Set background color for drawer item when was chose
		mLLAbout.setBackgroundColor(Color.TRANSPARENT);
		mLLDashBoard.setBackgroundColor(getResources().getColor(R.color.green));
		// mLLFriends.setBackgroundColor(Color.TRANSPARENT);
		// mLLLogOff.setBackgroundColor(Color.TRANSPARENT);
		mLLGoalSettings.setBackgroundColor(Color.TRANSPARENT);
		// mLLDevice.setBackgroundColor(Color.TRANSPARENT);
		mLlUserProfile.setBackgroundColor(Color.TRANSPARENT);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.fitness, menu);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		/**
		 * Check if current page is Dash Board, show Exit dialog. Else show
		 * previous page
		 */
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
				this.finish();
				return false;
			} else {
				if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT
						| DashBoardFragment.IS_IN_DASHBOARD
						| DashBoardDetailFragment.IS_IN_DASHBOARD_DETAIL) {
					onClickBack();

					return false;
				}

			}
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// The action bar home/up action should open or close the drawer.
		// ActionBarDrawerToggle will take care of this.
		if (mAbdtToggle.onOptionsItemSelected(item)) {
			return false;
		}
		// Handle action buttons
		switch (item.getItemId()) {
		// case R.id.mi_scan_devices:
		// // Check blue-tooth on-off
		// checkBluetoothOnOff();
		// return false;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	
	/**
	 * Initial methods
	 */
	private void initialData(Bundle savedInstanceState) {
		// set a custom shadow that overlays the main content when the drawer
		// opens
		mDlDrawer
				.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

		// enable ActionBar application icon to behave as action to toggle nav
		// drawer
		getActionBar().setDisplayHomeAsUpEnabled(false);
		getActionBar().setHomeButtonEnabled(true);

		mAbdtToggle = new ActionBarDrawerToggle(this, mDlDrawer,
				R.drawable.ic_achieve_activemins_, 0, 0) {
			/** Called when a drawer has settled in a completely closed state. */
			@Override
			public void onDrawerClosed(View view) {
				super.onDrawerClosed(view);
				invalidateOptionsMenu(); // creates call to
				// onPrepareOptionsMenu()
			}

			/** Called when a drawer has settled in a completely open state. */
			@Override
			public void onDrawerOpened(View drawerView) {
				super.onDrawerOpened(drawerView);
				invalidateOptionsMenu();

				/**
				 * If pop up dialog was shown now, need close it
				 */
				if (DashBoardFragment.mPw != null) {
					DashBoardFragment.mPw.dismiss();
				}
				if (DashBoardDetailFragment.mPw != null) {
					DashBoardDetailFragment.mPw.dismiss();
				}

				/**
				 * Save current goal value also : Save into Shared Preferences
				 * and SingleTon
				 */
				Fragment mFragmentCurrent = getSupportFragmentManager()
						.findFragmentById(R.id.fr_content_activity_fitness);
				if (mFragmentCurrent.getClass().getSimpleName().toString()
						.equals(GoalSettingsFragment.class.getSimpleName())) {
					GoalSettingsFragment
							.saveGoalValueIntoSharedPreferences(mContextActivityFitness);
					GoalSettingsFragment.saveGoalValueIntoSingleTon();
				}
			}
		};
		mAbdtToggle.setDrawerIndicatorEnabled(true);

		// Set the list's click listener
		mDlDrawer.setDrawerListener(mAbdtToggle);

		if (savedInstanceState == null) {
			// Insert the fragment by replacing any existing fragment
			getSupportFragmentManager()
					.beginTransaction()
					.replace(R.id.fr_content_activity_fitness,
							new SplashScreenFragment()).addToBackStack(null)
					.commitAllowingStateLoss();
			getSupportFragmentManager().executePendingTransactions();

		}
	}

	// private void initialDialog() {
	// mDialogScanDevice = new Dialog(this);
	// mDialogScanDevice.requestWindowFeature(Window.FEATURE_NO_TITLE);
	// mDialogScanDevice.setContentView(R.layout.dialog_scan_device);
	//
	// Constants.utils.initialFullScreenDialog(mDialogScanDevice);
	// }

	private void initialVariables() {
		mDlDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
		mIbtnAvatarInDrawer = (ImageButton) findViewById(R.id.ibtn_avatar_in_drawer);
		mLLAbout = (LinearLayout) findViewById(R.id.ll_about_in_fitness);
		mLLDashBoard = (LinearLayout) findViewById(R.id.ll_dash_board_in_fitness);
		// mLLDevice = (LinearLayout) findViewById(R.id.ll_device_in_fitness);
		// mLLFriends = (LinearLayout)
		// findViewById(R.id.ll_friends_in_activity);
		mLLGoalSettings = (LinearLayout) findViewById(R.id.ll_goal_settings_in_fitness);
		mLlUserProfile = (LinearLayout) findViewById(R.id.ll_user_profile_in_fitness);
		mTvNickNameBesideAvatar = (TextView) findViewById(R.id.tv_nickname_in_drawer);
		mTvNickNameBesideDevice = (TextView) findViewById(R.id.tv_nickname_device_in_drawer);
	}

	/**
	 * Basic methods
	 */
	private void setupActionBar() {
		getActionBar().setDisplayShowCustomEnabled(true);
		getActionBar().setDisplayShowTitleEnabled(false);
		getActionBar().setIcon(R.drawable.ibtn_drawer);
		getActionBar().setDisplayShowHomeEnabled(true);

		LayoutInflater inflator = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflator.inflate(R.layout.action_bar, null);

		mBtnLeftActionBar = (Button) v
				.findViewById(R.id.btn_left_in_action_bar);
		// mIbtnRightActionBar = (ImageButton) v
		// .findViewById(R.id.btn_right_in_action_bar);
		mIvActionBar = (ImageView) v.findViewById(R.id.iv_action_bar);
		mLLLeftActionBar = (LinearLayout) v
				.findViewById(R.id.ll_left_in_action_bar);
		mTvTitle = (TextView) v.findViewById(R.id.tv_title_in_action_bar);

		getActionBar().setCustomView(v);
	}
}
